<?php

/**
* @current image.php
* @author   LiuYang <liu_yang@haibao.com>
* @date 2016年12月8日 下午4:58:44
*/

define('IN_ECS', true);

require(dirname(__FILE__) . '/includes/init.php');

require(dirname(dirname(__FILE__)).'/includes/request.php');

global $db;

$act = Request::get('act')?Request::get('act'):'';
/**
 * 保存上传图片
 */
if($act == 'upload'){
    $dataArr = array();
    $fileInfo = Request::file('file');
    $storagePath = getUploadStoragePath($fileInfo['name']);
    list($width, $height) = getimagesize($fileInfo['tmp_name']);
    $dataArr['Filename'] = $storagePath;
    $dataArr['Width'] = $width;
    $dataArr['Height'] = $height;
    $dataArr['Size'] = $fileInfo['size'];
    $dataArr['CreateBy'] = $GLOBALS['_SESSION']['admin_id'];
    $dataArr['CreateTime'] =  date('Y-m-d H:i:s');
    $dataArr['IsWater'] = 0;
    $dataArr['IndexTime'] = date('Y-m-d H:i:s');
    $dataArr['Level'] = 1;
    $db->add('shopdata_imagelist',$dataArr);
    generateImage($storagePath, file_get_contents($fileInfo['tmp_name']));
    $data = array(
        'ret' => 1,
        'info' => json_encode($dataArr)
    );
    response($data);
}
function getUploadStoragePath($orgionName){
    $basePath = '/uploads/'.date('Y').DIRECTORY_SEPARATOR.date('md').DIRECTORY_SEPARATOR.microtime(true);
    $extension = pathinfo($orgionName);
    $basePath .= '.' . strtolower(isset($extension['extension']) ? $extension['extension'] : 'jpg');
    return str_replace(array('/', '\\'), '/', $basePath);
} 

/**
 * 保存生图片
 */
function generateImage($path, $stream){
	$savePath = getSaveImagePath($path);
	createDir($savePath);
	file_put_contents($savePath, $stream, LOCK_EX);
}

 /**
 * 获取文件保存路径
 */
function getSaveImagePath($path){
	$path = '/'. ltrim($path,'/');
	return dirname(dirname(dirname(__FILE__))) . $path;
}

/**
 * 创建文件保存路径
 */
function createDir($path){
	$path = pathinfo( $path );
	return is_writable($path['dirname']) ?: mkdir($path['dirname'], 750, true);
}
?>